//
//  SSEmoticons.swift
//  SSEmoticon
//
//  Created by stevenSu on 15/8/6.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit

class SSEmoticonPackage: NSObject {
    var id: String?
    var group_name_cn: String?
    lazy var emoticons = [SSEmoticon]()
    private static let bundlePath = (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons.bundle")
    // 保证只加载一次
    static let packages = SSEmoticonPackage.loadEmoticonPackages()
    
    init(id: String) {
        super.init()
        self.id = id
    }
    
    class func emoticonText(text: String, font: UIFont) -> NSAttributedString {
        let regex = try! NSRegularExpression(pattern: "\\[.*?\\]", options: NSRegularExpressionOptions.DotMatchesLineSeparators)
        let result = regex.matchesInString(text, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: text.characters.count))
        
        var count = result.count
        var foundEmoticon: SSEmoticon?
        let strM = NSMutableAttributedString(string: text)
        while count > 0 {
            --count
            let range = result[count].rangeAtIndex(0)
            // [haha]
            let emoticonStr = (text as NSString).substringWithRange(range)
            for package in SSEmoticonPackage.packages {
                foundEmoticon = package.emoticons.filter({ (e) -> Bool in
                    return e.chs == emoticonStr
                }).last
                if foundEmoticon != nil {
                    break
                }
            }
            if foundEmoticon != nil {
                let attrStr = SSEmoticonAttachment.createAttrString(foundEmoticon!, font: font)
                strM.replaceCharactersInRange(range, withAttributedString: attrStr)
            }
        }
        strM.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: strM.length))
        return strM
    }
    
    class func saveRecentEmoticon(emoticon: SSEmoticon) {
        let package = packages[0]
        var emoticons = package.emoticons
        if !emoticons.contains(emoticon) {
            emoticons.removeLast()
            emoticons.append(emoticon)
        }
        emoticons = emoticons.sort { (e1, e2) -> Bool in
            e1.clickCount > e2.clickCount
        }
        if !package.emoticons.contains(emoticon) {
            emoticons.removeLast()
            emoticons.append(SSEmoticon(isRemove: true))
        }
        package.emoticons = emoticons
    }
    
    private class func loadEmoticonPackages() -> [SSEmoticonPackage] {
        print("加载表情包")
        let dict = NSDictionary(contentsOfFile: (bundlePath as NSString).stringByAppendingPathComponent("emoticons.plist")) as! [String: AnyObject]
        let packages = dict["packages"] as! [[String: AnyObject]]
        var emoticonPackages = [SSEmoticonPackage]()
        // 设置最近
        let recentPackage = SSEmoticonPackage(id: "")
        recentPackage.group_name_cn = "最近"
        recentPackage.loadEmptyEmoticons(20)
        emoticonPackages.append(recentPackage)
        for packageDict in packages {
            let id = packageDict["id"] as? String ?? ""
            let emoticonPackage = SSEmoticonPackage(id: id).loadEmoticons().loadDeleteEmoticons()
            emoticonPackages.append(emoticonPackage)
        }
//        print(emoticonPackages)
        return emoticonPackages
    }
    
    private func loadEmoticons() -> Self {
            
        let path = ((SSEmoticonPackage.bundlePath as NSString).stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent("info.plist")
        let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]
        
        group_name_cn = dict["group_name_cn"] as? String ?? ""
//        emoticons = [SSEmoticon]()
        for emoticonDict in dict["emoticons"] as! [[String: String]] {
            let emoticon = SSEmoticon(dict: emoticonDict, id: id!)
            emoticons.append(emoticon)
            
        }
        return self
    }
    
    private func loadDeleteEmoticons() -> Self {
        // 单页计数
        var singlePageCount = 0
        // 先算返回
        for emoticon in emoticons {
            singlePageCount++
            if singlePageCount == 20 {
//                print(emoticons.indexOf(emoticon)!)
                emoticons.insert(SSEmoticon(isRemove: true), atIndex: emoticons.indexOf(emoticon)! + 1)
                singlePageCount = 0
            }
        }
        // 再算补足空格
        let count = emoticons.count
        if count % 21 != 0 {
            loadEmptyEmoticons(20 - count % 21)
        }
        
        return self
    }
    
    private func loadEmptyEmoticons(count: Int) {
        for _ in 0..<count {
            emoticons.append(SSEmoticon(isRemove: false))
        }
        emoticons.append(SSEmoticon(isRemove: true))
    }
    
    override var description: String {
        let dict = dictionaryWithValuesForKeys(["id", "group_name_cn", "emoticons"])
        return "\(dict)"
    }
}

class SSEmoticon: NSObject {
    var id: String?
    var chs: String?
    var png: String? {
        didSet {
            pngPath = ((SSEmoticonPackage.bundlePath as NSString).stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent(png!)
        }
    }
    var pngPath: String?
    var code: String? {
        didSet {
            emojiString = String.emojiString(code!)
        }
    }
    var emojiString: String?
    // compose_emotion_delete
    var isRemoveBtn = false
    var clickCount = 0
    
    init(isRemove: Bool) {
        super.init()
        isRemoveBtn = isRemove
    }
    
    init(dict: [String: String], id: String) {
        super.init()
        self.id = id
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let dict = dictionaryWithValuesForKeys(["chs", "png", "code", "isRemoveBtn", "clickCount"])
        return "\(dict)"
    }
}